<?php

namespace app\controllers;


use Yii;
use yii\data\ArrayDataProvider;
use yii\web\MethodNotAllowedHttpException;
use yii\web\NotFoundHttpException;
use zonday\weixin\api;

class GroupsController extends BaseController
{
    public function actionIndex()
    {
        $groupApi = new api\Groups();
        $groups = $groupApi->get()['groups'];
        $dataProvider = new ArrayDataProvider(['allModels' => $groups]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionCreate()
    {
        $request = Yii::$app->getRequest();
        if ($request->isPost && $name = $request->post('name')) {
            $groupApi = new api\Groups();
            $groupApi->create($name);
            Yii::$app->getSession()->setFlash('success', '创建分组成功');
            return $this->redirect(['index']);
        } else {
            $name = '';
        }

        return $this->render('create', [
            'name' => $name,
        ]);
    }

    public function actionUpdate($id)
    {
        $groupApi = new api\Groups();
        $groups = $groupApi->get()['groups'];
        foreach ($groups as $group){
            if ($group['id'] == $id) {
                $name = $group['name'];
                break;
            }
        }

        if (!isset($name)) {
            throw new NotFoundHttpException('分组未找到');
        }

        $request = Yii::$app->getRequest();
        if ($request->isPost && $name = $request->post('name')) {
            $groupApi->update($id, $name);
            Yii::$app->getSession()->setFlash('success', '更新分组成功');
            return $this->redirect(['index']);
        }

        return $this->render('update', [
            'name' => $name,
        ]);
    }

    public function actionDelete($id)
    {
        $groupApi = new api\Groups();
        $request = Yii::$app->getRequest();
        if ($request->isPost && $id) {
            $groupApi->delete($id);
            Yii::$app->getSession()->setFlash('success', '删除分组成功');
            return $this->redirect(['index']);
        } else {
            throw new MethodNotAllowedHttpException();
        }
    }
}